import asyncio
from concurrent.futures import ThreadPoolExecutor
from .views.ws import manager
from .utils.log import get_logger, get_json_logger
from datetime import datetime, timedelta
import json

logger = get_logger(__name__)     
json_logger = get_json_logger() 

loop = asyncio.get_event_loop()
executor = ThreadPoolExecutor()


def async_msg(msg, status="scp", level="info", log=True, type=None):
    current_time = (datetime.utcnow() + timedelta(hours=8)).strftime('%Y-%m-%d %H:%M:%S')
    json_data = {"msg": msg, "time": current_time, "status": status, "level": level}

    if type:
        json_data["type"] = type

    try:
        asyncio.run(manager.broadcast_json(json_data))
    except Exception as e:
        logger.error(f"发送 ws 出错, 异常信息: {e}")

    if log:
        json_logger.info(json.dumps(json_data, ensure_ascii=False))